/*
 * @Description: 编辑用户弹窗组件
 * @Author: Rfan
 * @Date: 2022-04-25 16:45:04
 * @LastEditTime: 2022-09-05 18:24:39
 */

import { Button, Form, Modal } from 'antd';
import { FC, useEffect, useState } from 'react';
import { useOrgAndUserContext } from '../../contexts/OrgAndUserContext';
import type { ICommonDialog } from '@/interfaces/global';
import UserFormItems from './common/UserFormItems';

interface IEditUserDialogProps extends ICommonDialog {
  data: any;
}

const EditUserDialog: FC<IEditUserDialogProps> = (props: any) => {
  const { visible, data, onClose } = props;
  const { addUserFunc } = useOrgAndUserContext();

  // 角色调整标识
  const [roleFlag, setRoleFlag] = useState(false);
  const [form] = Form.useForm();

  useEffect(() => {
    if (visible) {
      form.setFieldsValue(data);
    }
  }, [visible]);

  /**
   * @description: 角色选择框有变动将调整标识设为true
   */
  const onRoleChange = () => {
    setRoleFlag(true);
  };

  // 提交表单
  const submitFunc = () => {
    form.submit();
  };

  // 编辑用户
  const onFinish = (values: any) => {
    delete values.repassword;
    const user = { ...data, ...values };
    addUserFunc({ user, updateUserRole: roleFlag }, 'edit').then(() => {
      onClose();
    });
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };
  const onCancel = () => {
    onClose();
  };

  return (
    <Modal
      destroyOnClose
      title="编辑用户"
      visible={visible}
      width={800}
      onCancel={onCancel}
      footer={[
        <Button key="back" onClick={onCancel}>
          取消
        </Button>,
        <Button key="submit" type="primary" onClick={submitFunc}>
          编辑用户
        </Button>
      ]}
    >
      <Form
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
        preserve={false}
        form={form}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
      >
        <UserFormItems visible={visible} onRoleChange={onRoleChange} />
      </Form>
    </Modal>
  );
};

export default EditUserDialog;
